package com.keba.lamp.complaint.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.keba.basic.base.R;
import com.keba.basic.base.request.PageParams;
import com.keba.basic.interfaces.echo.EchoService;
import com.keba.lamp.complaint.entity.Case;
import com.keba.lamp.complaint.entity.Defendant;
import com.keba.lamp.complaint.entity.Plaintff;
import com.keba.lamp.complaint.service.CaseService;
import com.keba.lamp.complaint.service.DefendantService;
import com.keba.lamp.complaint.service.PlaintffService;
import com.keba.lamp.complaint.vo.result.OnlineCaseResultVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.keba.basic.base.controller.SuperController;
import com.keba.lamp.complaint.service.OnlineCaseFilingService;
import com.keba.lamp.complaint.entity.OnlineCaseFiling;
import com.keba.lamp.complaint.vo.save.OnlineCaseFilingSaveVO;
import com.keba.lamp.complaint.vo.update.OnlineCaseFilingUpdateVO;
import com.keba.lamp.complaint.vo.result.OnlineCaseFilingResultVO;
import com.keba.lamp.complaint.vo.query.OnlineCaseFilingPageQuery;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 在线立案
 * </p>
 *
 * @author twg
 * @date 2025-07-27 20:56:45
 * @create [2025-07-27 20:56:45] [twg] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/onlineCaseFiling")
@Tag(name = "在线立案")
public class OnlineCaseFilingController extends SuperController<OnlineCaseFilingService, Long, OnlineCaseFiling, OnlineCaseFilingSaveVO, OnlineCaseFilingUpdateVO, OnlineCaseFilingPageQuery, OnlineCaseFilingResultVO> {
    private final EchoService echoService;

    private final CaseService caseService;

    private final PlaintffService plaintffService;

    private final DefendantService defendantService;

    @Override
    public EchoService getEchoService() {
        return echoService;
    }

    @Override
    public void handlerQueryParams(PageParams<OnlineCaseFilingPageQuery> params) {
        String caseName = params.getModel().getCaseName();
        String caseType = params.getModel().getCaseType();
        String caseState = params.getModel().getCaseState();
        String createdTime = params.getModel().getCreatedTime();
        if (StrUtil.isNotBlank(caseName) || StrUtil.isNotBlank(caseType) || StrUtil.isNotBlank(caseState)) {
            List<Case> cases = caseService.list(Wrappers.<Case>lambdaQuery().like(StrUtil.isNotBlank(caseName), Case::getCaseName, caseName).eq(StrUtil.isNotBlank(caseType), Case::getCaseType, caseType).eq(StrUtil.isNotBlank(caseState), Case::getCaseState, caseState).ge(StrUtil.isNotBlank(createdTime), Case::getCreatedTime, DateUtil.beginOfDay(DateUtil.parseDate(createdTime))).le(StrUtil.isNotBlank(createdTime), Case::getCreatedTime, DateUtil.endOfDay(DateUtil.parseDate(createdTime))));
            if (CollectionUtil.isNotEmpty(cases)) {
                params.getExtra().put("caseId_in", cases.stream().map(Case::getId).collect(Collectors.toList()));
            }
        }
    }

    @Override
    public void handlerResult(IPage<OnlineCaseFilingResultVO> page) {
        List<OnlineCaseFilingResultVO> results = page.getRecords();
        if (CollectionUtil.isEmpty(results)) {
            return;
        }
        List<Case> cases = caseService.listByIds(results.stream().map(OnlineCaseFilingResultVO::getCaseId).collect(Collectors.toList()));
        List<Long> caseIds = cases.stream().map(Case::getId).collect(Collectors.toList());
        List<Defendant> defendants = defendantService.list(Wrappers.<Defendant>lambdaQuery().in(Defendant::getCaseId, caseIds));
        List<Plaintff> plaintffs = plaintffService.list(Wrappers.<Plaintff>lambdaQuery().in(Plaintff::getCaseId, caseIds));
        Map<Long, String> defendantMap = defendants.stream().collect(Collectors.groupingBy(Defendant::getCaseId, Collectors.mapping(Defendant::getName, Collectors.joining(","))));
        Map<Long, String> plaintffMap = plaintffs.stream().collect(Collectors.groupingBy(Plaintff::getCaseId, Collectors.mapping(Plaintff::getName, Collectors.joining(","))));

        Map<Long, Case> caseMap = cases.stream().collect(Collectors.toMap(Case::getId, Function.identity()));
        results.forEach(i -> {
            i.setCaseName(caseMap.get(i.getCaseId()).getCaseName()).setBizType(caseMap.get(i.getCaseId()).getBizType())
                    .setCourtName(caseMap.get(i.getCaseId()).getCourtName())
                    .setCaseType(caseMap.get(i.getCaseId()).getCaseType())
                    .setParticipants(StrUtil.format("原告：{}\n" + "被告：{}", plaintffMap.get(i.getCaseId()), defendantMap.get(i.getCaseId())));
        });
    }


    /**
     * 通过案件名称模糊搜索
     */
    @Operation(summary = "在线立案-通过案件名称模糊搜索")
    @GetMapping("/listByCaseName")
    public R<List<OnlineCaseResultVO>> listByCaseName(@RequestParam String caseName) {
        return R.success(superService.listByCaseName(caseName));
    }



}


